<template>
  <view>
    <view class="form-container">
      <uni-forms ref="form" :modelValue="formData" :rules="rules" labelPosition="top">
        <cu-cell-group>
          <uni-forms-item name="workTypeFlag">
            <cu-cell class="cu-cell--select-v2" title="特殊作业类型" required>
              <CuSelectV2
                v-model="formData.workTypeFlag"
                title="特殊作业类型"
                placeholder="请选择"
                label-key="categoryName"
                value-key="categoryFlag"
                :options="specialWorkType"
                @change="onSpecialWorkTypeChange"
              />
            </cu-cell>
          </uni-forms-item>
          <uni-forms-item v-if="workTypeLevel.length" name="level">
            <cu-cell class="cu-cell--select-v2" :title="levelFormLabels[formData.workTypeFlag]" required>
              <CuSelectV2
                v-model="formData.level"
                :title="levelFormLabels[formData.workTypeFlag]"
                placeholder="请选择"
                label-key="title"
                value-key="level"
                :options="workTypeLevel"
                @change="onWorkLevelChange"
              />
            </cu-cell>
          </uni-forms-item>

          <uni-forms-item name="areaId">
            <cu-cell
              title="作业区域"
              required
              link
              placeholder="请选择"
              :description="formData.areaName"
              @click="showAreaSelector()"
            ></cu-cell>
          </uni-forms-item>

          <uni-forms-item name="operationPoint">
            <cu-cell title="作业点" required>
              <input
                type="text"
                v-model="formData.operationPoint"
                placeholder="请输入(限20字)"
                class="input"
                placeholder-class="input-placeholder"
                maxlength="20"
              />
            </cu-cell>
          </uni-forms-item>

          <uni-forms-item name="directorId">
            <cu-cell
              :title="formData.workTypeFlag === specialWorkTypeEnum.ELECTRIC ? '用电单位负责人' : '作业单位负责人'"
              required
              link
              placeholder="请选择"
              :description="formData.directorName"
              @click="showUserSelector()"
            ></cu-cell>
          </uni-forms-item>

          <uni-forms-item>
            <cu-cell
              :title="formData.workTypeFlag === specialWorkTypeEnum.ELECTRIC ? '用电单位' : '作业单位'"
              :description="formData.unitName"
            ></cu-cell>
          </uni-forms-item>

          <uni-forms-item name="workContent">
            <cu-cell title="作业内容" column required>
              <uni-easyinput
                type="textarea"
                v-model="formData.workContent"
                placeholder="请输入(限50字)"
                maxlength="50"
              />
            </cu-cell>
          </uni-forms-item>

          <uni-forms-item name="riskIdentificationResult">
            <cu-cell
              title="风险辨识结果"
              required
              link
              placeholder="请选择"
              :description="formData.riskIdentificationResult"
              @click="showRiskResult()"
            ></cu-cell>
          </uni-forms-item>
        </cu-cell-group>
      </uni-forms>
    </view>

    <view class="button-wrap">
      <button class="u-button block" @click="submit">保存</button>
    </view>

    <!-- 用户选择器 v2 -->
    <cu-dept-user-select
      ref="deptUserSelectRef"
      :checkList="deptUserSelectProps.checkList"
      @change="onDeptUserChange"
    ></cu-dept-user-select>

    <cu-tree-select
      ref="treeSelectRef"
      :checkList="treeSelectProps.checkList"
      :request-api="getFactoryArea"
      :disabled-node-level="[1]"
      label-key="areaName"
      value-key="areaId"
      children-key="childList"
      @change="onFactoryAreaChange"
    />
  </view>
</template>
<script>
import CuSelectV2 from '@/components/cu-select-v2/cu-select-v2.vue'
import CuCell from '@/components/cu-cell/cu-cell.vue'
import CuCellGroup from '@/components/cu-cell/cu-cell-group.vue'
import { addProjectWork, getFactoryArea, getSpecialWorkType } from '@/api/spw/project'
import { specialWorkTypeEnum } from '@/utils/constant'
import { queryTicketWorkTypeLevel } from '@/api/spw/ticketApply'
import CuDeptUserSelect from '@/components/cu-dept-user-select/cu-dept-user-select.vue'
import CuTreeSelect from '@/components/cu-tree-select/cu-tree-select.vue'
import UGap from '@/uni_modules/uview-ui/components/u-gap/u-gap.vue'

export default {
  components: { UGap, CuDeptUserSelect, CuCellGroup, CuCell, CuSelectV2, CuTreeSelect },
  onLoad(query) {
    this.projectInfoId = query.projectInfoId
    this.projectId = query.projectId
    getSpecialWorkType().then(({ data }) => {
      this.specialWorkType = data
    })

    // 项目申报，作业票编辑
    const eventChannel = this.getOpenerEventChannel()
    eventChannel.on('project-ticket:form', (data) => {
      this.formData = {
        ...data.data
      }
      this.getWorkTypeLevel(this.formData.workTypeFlag)
    })
  },
  data() {
    return {
      loading: false,
      specialWorkTypeEnum,
      specialWorkType: [],
      workTypeLevel: [],
      levelFormLabels: {
        [specialWorkTypeEnum.FIRE]: '动火作业级别',
        [specialWorkTypeEnum.HIGH]: '作业类别',
        [specialWorkTypeEnum.LIFTING]: '作业级别'
      },
      deptUserSelectProps: {
        checkList: []
      },
      treeSelectProps: {
        checkList: []
      },
      formData: {
        workTypeLabel: '',
        workTypeFlag: '',
        level: '',
        levelLabel: '',
        operationPoint: '',
        unitId: '',
        unitName: '',
        unitType: '',
        directorId: '',
        directorName: '',
        workContent: '',
        areaName: '',
        areaId: '',
        riskIdentification: [],
        riskIdentificationResult: ''
      },
      rules: {
        workTypeFlag: {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            }
          ]
        },
        level: {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            }
          ]
        },
        areaId: {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            }
          ]
        },
        operationPoint: {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            }
          ]
        },
        directorId: {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            }
          ]
        },
        workContent: {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            }
          ]
        },
        riskIdentificationResult: {
          rules: [
            {
              required: true,
              errorMessage: '不能为空'
            }
          ]
        }
      }
    }
  },
  methods: {
    getFactoryArea,
    onSpecialWorkTypeChange() {
      const item = this.specialWorkType.find((pet) => pet.categoryFlag === this.formData.workTypeFlag)
      this.formData.workTypeLabel = item.categoryName
      this.formData.level = ''
      this.formData.levelLabel = ''
      this.workTypeLevel = []
      this.getWorkTypeLevel(this.formData.workTypeFlag)
    },
    onWorkLevelChange() {
      const row = this.workTypeLevel.find((pet) => pet.level === this.formData.level)
      this.formData.levelLabel = row.title
    },
    getWorkTypeLevel(val) {
      if ([specialWorkTypeEnum.FIRE, specialWorkTypeEnum.HIGH, specialWorkTypeEnum.LIFTING].includes(val)) {
        queryTicketWorkTypeLevel(val).then(({ data }) => {
          this.workTypeLevel = data ?? []
        })
      }
    },
    showUserSelector() {
      this.deptUserSelectProps.checkList = [
        {
          userId: this.formData.directorId,
          name: this.formData.directorName,
          deptId: this.formData.unitId,
          deptName: this.formData.unitName,
          deptProperty: this.formData.unitType
        }
      ]
      this.$refs.deptUserSelectRef.open()
    },
    onDeptUserChange(val) {
      this.formData.directorId = val[0].userId
      this.formData.directorName = val[0].name
      this.formData.unitId = val[0].deptId ?? ''
      this.formData.unitName = val[0].deptName ?? ''
      this.formData.unitType = val[0].deptProperty ?? ''
    },

    // 风险辨识结果
    showRiskResult() {
      uni.navigateTo({
        url: '/pages/jobSlip/work-ticket/risk-result',
        events: {
          'risk-result:form:success': (data) => {
            const types = data.reduce((risk, cur) => risk.concat(cur.riskType), [])
            this.$set(this.formData, 'riskIdentificationResult', types.join(','))
            this.formData.riskIdentification = data
          }
        },
        success: (res) => {
          res.eventChannel.emit('riskResultData', this.formData.riskIdentification)
        }
      })
    },
    async submit() {
      if (this.projectId && this.projectInfoId) {
        await this.asyncSubmit()
        return
      }
      await this.$refs.form.validate()
      const eventChannel = this.getOpenerEventChannel()
      eventChannel.emit('project-ticket:form:success', this.formData)
      await uni.navigateBack()
    },

    async asyncSubmit() {
      if (this.loading) {
        return
      }
      await this.$refs.form.validate()
      this.loading = true
      uni.showLoading({
        title: '正在保存'
      })
      const req = {
        ...this.formData,
        projectId: this.projectId,
        projectInfoId: this.projectInfoId
      }
      console.log('req', req)
      const res = await addProjectWork(req)
      const eventChannel = this.getOpenerEventChannel()
      res.data.ticketWorkLevel = this.formData.level
      res.data.ticketWorkLevelLabel = this.formData.levelLabel
      res.data.riskIdentificationResult = this.formData.riskIdentificationResult
      eventChannel.emit('new-ticket:form:success', res.data)
      this.$modal.msg('新增成功，请填写作业票信息！')
      this.loading = false
      setTimeout(() => {
        uni.hideLoading()
        uni.navigateBack()
      }, 1000)
    },
    showAreaSelector() {
      this.treeSelectProps.checkList = [
        {
          areaId: this.formData.areaId,
          areaName: this.formData.areaName
        }
      ]
      this.$refs.treeSelectRef.open()
    },
    onFactoryAreaChange(val) {
      this.formData.areaId = val[0].areaId
      this.formData.areaName = val[0].areaName
    }
  }
}
</script>

<style scoped lang="scss">
.button-wrap {
  padding: 20px 30rpx;
}
</style>
